package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.louwowo.cache.key.RedisKeys;
import cn.wolfcode.luowowo.member.domain.UserInfo;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    private CookieUtil(){}

    public static void addCookie(String key,String value,int time,HttpServletResponse resp){
        //往cookie中存入key和value
        Cookie cookie = new Cookie(key,value);
        //设置cookie作用域
        cookie.setPath("/");
        //设置cookie的存活时间
        cookie.setMaxAge(time);
        //响应cookie回去
        resp.addCookie(cookie);
    }

    public static String getToken(HttpServletRequest req,HttpServletResponse resp){
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    //延长cookie的失效时间,并重新共享cookie
                    cookie.setMaxAge(RedisKeys.USERINFO_LOGIN.getTime().intValue());
                    //延长失效时间时候，要重新响应给页面，不然页面的cookie还是之前的
                    resp.addCookie(cookie);
                    return cookie.getValue();
                }
            }
        }
        return null;
    }



}
